<template>
  <div class="app-container">
    <el-card v-loading="loading" class="tree-card">
      <TreeTools
        :item="header"
        :isshow="false"
        @dialogShow="dialogShow"
      />
      <!-- tree树形组件 -->
      <el-tree :data="list" :props="defaultProps" default-expand-all>
        <!-- 作用域插槽 -->
        <!-- node：el-tree 底层的节点信息,相当于这里的defaultProps -->
        <!-- data：拿到的是每个节点的数据对象，相当于这里的list -->
        <template #default="{ data }">
          <TreeTools
            :item="data"
            @dialogShow="dialogShow"
            @delDepart="delDepart"
          />
        </template>
      </el-tree>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="dialogClose"
      @open="dialogOpen"
    >
      <!-- 表单内容 -->
      <el-form
        ref="deptRef"
        :model="formData"
        :rules="deptRules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入1-50个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入1-50个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select
            v-model="formData.manager"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="formData.introduce"
            type="textarea"
            placeholder="请输入1-300个字符"
          />
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartment,
  getManagerList,
  addDepartment,
  getDepartDetail,
  updateDepartment,
  delDepartment
} from '@/api'
import TreeTools from './components/tree-tools.vue'
import transTree from '@/utils/transTree'
// import findSon from '@/utils/findSon'
export default {
  components: {
    TreeTools
  },
  data() {
    //  部门编码自定义校验规则: 所有部门中不能出现相同的部门编码
    const validateCode = (rule, value, callback) => {
      // 排除编辑下，没有修改的校验
      if (this.formData.id && value === this.formData.code) {
        callback()
        return
      }
      const isSome = this.originList.some((item) => item.code === value)
      isSome ? callback(new Error('部门编码已存在！')) : callback()
    }
    // 部门名称自定义校验规则: 同级部门中不能出现相同的部门名称
    const validateName = (rule, value, callback) => {
      let broArr = []
      if (this.formData.id) {
        if (value === this.currentNode.name) {
          callback()
          return
        } else {
          broArr = this.originList.filter(
            (item) => item.pid === this.currentNode.pid
          )
        }
      } else {
        // 找到所有的同级部门
        broArr = this.originList.filter(
          (item) => item.pid === this.currentNode.id
        )
      }
      // 只要当前添加的部门名称和任意一个同级部门的名称有相等，就不通过校验
      const isSome = broArr.some((item) => item.name === value)
      isSome ? callback(new Error('部门名称已存在！')) : callback()
    }
    return {
      // 部门原始数据
      originList: [],
      // 部门数据列表(处理过的，带有children字段)
      list: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      header: {
        name: '',
        manager: '',
        id: ''
      },
      // 控制弹窗显示与隐藏
      dialogVisible: false,
      // 表单数据
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      // 表单校验规则
      deptRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          },
          { validator: validateCode, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '长度在 1 到 300 个字符',
            trigger: 'blur'
          }
        ]
      },
      // 当前操作的父节点数据
      currentNode: {},
      // 负责人列表
      managerList: [],
      // 页面加载
      loading: false
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑子部门' : '添加子部门'
    }
  },
  created() {
    this.fetchDepartment()
  },
  methods: {
    // 获取部门列表
    async fetchDepartment() {
      this.loading = true
      try {
        const { data } = await getDepartment()
        // console.log(data)
        // 存储原始数据，全部部门
        this.originList = data.depts
        // console.log(this.originList)
        this.list = transTree(data.depts)
        // this.list = findSon(data.depts, '')
        this.header.name = data.companyName
        this.header.manager = data.companyManage
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    // 弹窗关闭之后触发
    dialogClose() {
      // 重置表单及校验规则
      // resetFields() 用于将表单的数据重置为初始值，并且将表单校验移除
      this.$refs.deptRef.resetFields()
      this.dialogVisible = false
      this.formData = {}
    },
    // 根据ID查询部门详情
    async getDepartment(id) {
      const { data } = await getDepartDetail(id)
      // console.log(data)
      this.formData = data
    },
    // 子传父，自定义事件
    dialogShow(val, type) {
      if (type === 'edit') {
        this.getDepartment(val.id)
      }
      this.dialogVisible = true
      // console.log(val)
      this.currentNode = val
    },
    // 弹窗打开的回调
    async dialogOpen() {
      const { data } = await getManagerList()
      // console.log(data)
      this.managerList = data
    },
    // 表单提交事件
    submit() {
      // 兜底校验
      this.$refs.deptRef.validate(async(valid) => {
        if (!valid) return
        if (this.formData.id) {
          // 根据formData是否有id，判断是编辑还是添加
          // 有id是编辑子部门
          const { data } = await updateDepartment(this.formData)
          console.log(data)
        } else {
          // 添加子部门
          await addDepartment({ ...this.formData, pid: this.currentNode.id })
        }
        // 关闭弹窗
        this.dialogClose()
        // 提示用户
        this.$message.success(`${this.title}成功！`)
        // 刷新列表
        this.fetchDepartment()
      })
    },
    // 删除子部门
    delDepart(val) {
      console.log(val)
      this.$confirm('是否删除该部门?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDepartment(val.id)
        this.$message.success('删除成功！')
        // 刷新列表
        this.fetchDepartment()
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  .tree-card {
    padding: 30px;
  }
}
</style>
